package com.appspot.inkisapi;

import in.jsonrpc.server.JsonRpcServer;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * All requests are made to this servlet by the client.<p>
 * The servlet reads configuration parameters, initializes
 * servers and loads services into servers dynamically.<p>
 * Then it checks the request URI and/or content type of
 * the request in order to determine web service method and
 * have appropriated server to take care of the request.
 * By the way, if some conditions are not passed it will sends
 * error respond to the client instead of forwarding the request
 * to the appropriated server.
 * <p>
 * Currently, only valid JSON_RPC requests are accepted.
 * @author 7inpham@gmail.com
 * @version 0.1
 */
public class DevServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(DevServlet.class.getName());
	private JsonRpcServer jsonRpcServer;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		jsonRpcServer = new JsonRpcServer();
		log.info("Inititialize servers and services");
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.service(req, resp);
		if (req.getRequestURI().equals("rpc")){
			if (req.getContentType() != null){
				doPost(req, resp);
			} else {
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			}
		}
		if (req.getRequestURI().equals("rest")){
			
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (req.getContentType().startsWith("application/json")){
			jsonRpcServer.execute(req, resp);
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
		}
	}
}
